package com.example.xiongmao.aspect;

import com.example.xiongmao.anno.AutoFill;
import com.example.xiongmao.constant.AutoFillConstant;
import com.example.xiongmao.context.BaseContext;
import com.example.xiongmao.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 公共字段自动填充切面类
 */
@Component
@Aspect
public class AutoFillAspect {
    @Before("execution(* com.example.xiongmao.mapper.*.*(..)) && @annotation(com.example.xiongmao.anno.AutoFill))")
    public void autoFill(JoinPoint joinPoint){
        System.out.println("开始进行公共字段自动填充....");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();  // 拿到方法签名
        Method method = methodSignature.getMethod();    //拿到方法
        AutoFill autoFill = method.getAnnotation(AutoFill.class);//拿到注解
        OperationType operationType = autoFill.value();// 拿到注解里面的值

        // 2 获取到目标方法的参数对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];    // 拿到就是实体对象

        // 3. 判断注解中属性值，如果是INSERT，就补充四个字段（创建时间、更新时间、创建人、更新人）
        try {
            if (operationType == OperationType.INSERT) {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);    // 传入的是id
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setCreateTime.invoke(entity,LocalDateTime.now());
                setUpdateTime.invoke(entity,LocalDateTime.now());
                setCreateUser.invoke(entity,BaseContext.getCurrentId());
                setUpdateUser.invoke(entity,BaseContext.getCurrentId());
                // 3. 判断注解中属性值，如果是UPDATE，就补充两个字段（更新时间、更新人）
            } else if (operationType == OperationType.UPDATE) {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(entity,LocalDateTime.now());
                setUpdateUser.invoke(entity, BaseContext.getCurrentId());
            }
        } catch (Exception e) {

        }
    }
}
